package com.linkme2night.controller;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;

import com.facebook.LoggingBehavior;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.Settings;
import com.facebook.android.Facebook;
import com.linkme2night.model.SocialNetwork_enum;

public class FacebookController {

	private Activity activity;
	private Session.StatusCallback statusCallback = new SessionStatusCallback();

	public FacebookController(Activity activity, Bundle savedInstanceState) {

		this.activity = activity;

		Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);

		Session session = Session.getActiveSession();
		if (session == null) {
			if (savedInstanceState != null) {
				session = Session.restoreSession(this.activity, null,
						statusCallback, savedInstanceState);
			}
			if (session == null) {
				session = new Session(this.activity);
			}
			Session.setActiveSession(session);
			if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
				session.openForRead(new Session.OpenRequest(this.activity)
						.setCallback(statusCallback));
			}
		}

		updateView();

	}

	public Session.StatusCallback getStatusCallback() {
		return statusCallback;
	}

	public void login() {
		Session session = Session.getActiveSession();
		if (!session.isOpened() && !session.isClosed()) {
			session.openForRead(new Session.OpenRequest(activity).setCallback(statusCallback));
		} else {
			Session.openActiveSession(activity, true, statusCallback);
		}
		Log.d("FB test", "session ID "+Session.getActiveSession().getApplicationId().toString());
		Log.d("FB test", "APP ID  627627057251695"); 
	}

	public void logout() {
		Session session = Session.getActiveSession();
		if (!session.isClosed()) {
			session.closeAndClearTokenInformation();
		}
	}
	
	private void updateView() {
        Session session = Session.getActiveSession();
        if (session.isOpened()) {
        	FrontController fc = new FrontController();
        	fc.openMenu(activity, SocialNetwork_enum.FACEBOOK);
        }
    }

	private class SessionStatusCallback implements Session.StatusCallback {
		@Override
		public void call(Session session, SessionState state,
				Exception exception) {
			 updateView();
		}
	}


}
